#ifndef __MY_SERVICE__
#define __MY_SERVICE__
#include"data.hpp"
#include"httplib.h"
#include<sstream>

extern cloud::DataManager* _data;

namespace cloud
{
    class Service
    {
    public:
        Service()
        {
            cloud::Config* tmp=cloud::Config::GetInstance();
            _server_ip=tmp->GetServerIp();
            _server_port=tmp->GetServerPort();
            _download_prefix=tmp->GetDownloadPrefix();
        }

        bool RunModul()
        {
            _server.Get("/",ShowList);
            _server.Get("/showlist",ShowList);
            _server.Post("/upload",UpLoad);
            std::string download=_download_prefix+"(.*)";
            _server.Get(download,DownLoad);
            _server.listen(_server_ip,_server_port);

            return true;
        }
    private:

        static std::string TimeToStr(time_t t)
        {
            return ctime(&t);
        }

        static std::string GetETag(const BackupInfo& info)
        {
            std::string str=FileUtil(info.real_path).FileName();
            str+="-";
            str+=info.fsize;
            str+="-";
            str+=info.mtime;

            return str;
        }
        static void DownLoad(const httplib::Request& req,httplib::Response& rsp)
        {
            auto url=req.path;
            BackupInfo info;
            if(_data->GetOneByURL(url,&info)==false)
            {
                rsp.status=400;
                return;
            }

            if(info.pack_flag==true)
            {
                FileUtil fu(info.pack_path);
                fu.UnCompress(info.real_path);
                fu.Remove();
                info.pack_flag=false;
                _data->Update(info);
            }

            FileUtil fu(info.real_path);
            bool ret=false;
            if(req.has_header("If-Range"))
            {
                std::string str=req.get_header_value("If-Range");
                if(str==GetETag(info))
                {
                    ret=true;
                }
            }
            if(ret==false)
            {
                std::string body;
                fu.GetContent(&body);
                rsp.body = body;
                rsp.set_header("Content-Type", "application/octet-stream");
                rsp.set_header("Accept-Ranges", "bytes");
                rsp.set_header("ETag", GetETag(info));
                rsp.status = 200;
            }
            else
            {
                fu.GetContent(&rsp.body);
                rsp.set_header("content-Type","application/octet-stream");
                rsp.set_header("Accept-Ranges","bytes");
                rsp.set_header("ETag", GetETag(info));
                rsp.status=206;
            }
        }
        static void ShowList(const httplib::Request& req,httplib::Response& rsp)
        {
            // std::vector<BackupInfo> arr;
            // _data->GetAll(&arr);
            // std::stringstream ss;
            // ss<<"<html><head><title>Download</title></head>";
            // ss<<"<body><h1>Download</h1><table>";
            // for(int i=0;i<arr.size();i++)
            // {
            //     ss<<"<tr>";
            //     std::string filename=FileUtil(arr[i].real_path).FileName();
            //     ss<<"<td><a href='"<<arr[i].url<<"'>"<<filename<<"</a></td>";
            //     ss<<"<td align='right'>"<<TimeToStr(arr[i].mtime)<<"</td>";
            //     ss<<"<td align='right'>"<<(arr[i].fsize/1024)<<"k</td>";
            // }

            // ss<<"</table></body></html>";

            // rsp.body=ss.str();
            // rsp.set_header("Content-Type","text/html");
            // rsp.status=200;

            std::vector<BackupInfo> arr;
    _data->GetAll(&arr);
    
    std::stringstream ss;
    ss << R"(<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文件下载中心</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', 'Helvetica Neue', Arial, sans-serif;
        }
        
        :root {
            --primary: #4361ee;
            --primary-light: #4895ef;
            --secondary: #6c757d;
            --light: #f8f9fa;
            --border: #e9ecef;
            --text: #212529;
            --text-light: #6c757d;
            --success: #4cc9f0;
            --card-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
            --hover-shadow: 0 8px 16px rgba(0, 0, 0, 0.08);
        }
        
        body {
            background-color: #f5f7ff;
            color: var(--text);
            min-height: 100vh;
            padding: 40px 20px;
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        
        .container {
            width: 100%;
            max-width: 1200px;
            margin: 0 auto;
        }
        
        header {
            text-align: center;
            margin-bottom: 40px;
            padding: 30px 0;
        }
        
        h1 {
            font-size: 2.5rem;
            font-weight: 600;
            color: var(--text);
            margin-bottom: 15px;
            letter-spacing: -0.5px;
        }
        
        .subtitle {
            font-size: 1.1rem;
            color: var(--text-light);
            max-width: 600px;
            margin: 0 auto;
            line-height: 1.6;
        }
        
        .card {
            background: white;
            border-radius: 16px;
            box-shadow: var(--card-shadow);
            padding: 30px;
            margin-bottom: 30px;
            transition: all 0.3s ease;
            border: 1px solid var(--border);
        }
        
        .card:hover {
            box-shadow: var(--hover-shadow);
        }
        
        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 25px;
            flex-wrap: wrap;
            gap: 15px;
        }
        
        .card-title {
            font-size: 1.5rem;
            font-weight: 600;
            color: var(--text);
        }
        
        .file-count {
            background: var(--light);
            color: var(--text-light);
            padding: 6px 14px;
            border-radius: 50px;
            font-size: 0.9rem;
            font-weight: 500;
        }
        
        .search-box {
            position: relative;
            width: 100%;
            max-width: 400px;
        }
        
        .search-box input {
            width: 100%;
            padding: 14px 20px 14px 50px;
            border-radius: 12px;
            border: 1px solid var(--border);
            background: white;
            color: var(--text);
            font-size: 1rem;
            transition: all 0.3s ease;
        }
        
        .search-box input:focus {
            border-color: var(--primary-light);
            outline: none;
            box-shadow: 0 0 0 3px rgba(67, 97, 238, 0.15);
        }
        
        .search-box i {
            position: absolute;
            left: 20px;
            top: 50%;
            transform: translateY(-50%);
            color: var(--secondary);
        }
        
        .sort-options {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }
        
        .sort-btn {
            padding: 10px 18px;
            border-radius: 12px;
            background: var(--light);
            border: 1px solid var(--border);
            color: var(--text);
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 0.95rem;
            display: flex;
            align-items: center;
            gap: 8px;
            font-weight: 500;
        }
        
        .sort-btn:hover {
            background: #f0f2f5;
            border-color: #d0d5dd;
        }
        
        .sort-btn.active {
            background: var(--primary);
            border-color: var(--primary);
            color: white;
        }
        
        .sort-btn.active i {
            color: white;
        }
        
        .file-table {
            width: 100%;
            border-collapse: collapse;
        }
        
        .file-table th {
            padding: 16px 15px;
            text-align: left;
            font-weight: 600;
            font-size: 0.95rem;
            color: var(--text-light);
            border-bottom: 2px solid var(--border);
            cursor: pointer;
            user-select: none;
            transition: all 0.2s ease;
        }
        
        .file-table th:hover {
            color: var(--text);
        }
        
        .file-table th i {
            margin-left: 8px;
            font-size: 0.9rem;
            color: var(--secondary);
        }
        
        .file-table td {
            padding: 18px 15px;
            border-bottom: 1px solid var(--border);
        }
        
        .file-table tr:last-child td {
            border-bottom: none;
        }
        
        .file-table tr:hover td {
            background: #fafbff;
        }
        
        .file-link {
            color: var(--text);
            text-decoration: none;
            font-weight: 500;
            display: flex;
            align-items: center;
            gap: 14px;
            transition: all 0.3s ease;
        }
        
        .file-link:hover {
            color: var(--primary);
        }
        
        .file-icon {
            width: 40px;
            height: 40px;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            background: #edf2ff;
            color: var(--primary);
            font-size: 1.1rem;
        }
        
        .file-name {
            display: flex;
            flex-direction: column;
        }
        
        .file-name span {
            font-size: 1rem;
            font-weight: 500;
        }
        
        .file-name small {
            font-size: 0.85rem;
            color: var(--text-light);
            margin-top: 4px;
        }
        
        .file-date {
            font-size: 0.95rem;
            color: var(--text);
        }
        
        .file-size {
            font-weight: 500;
            color: var(--text);
        }
        
        .no-files {
            text-align: center;
            padding: 60px 20px;
        }
        
        .no-files i {
            font-size: 3.5rem;
            color: #dee2e6;
            margin-bottom: 20px;
        }
        
        .no-files h3 {
            font-size: 1.4rem;
            color: var(--text-light);
            margin-bottom: 10px;
            font-weight: 500;
        }
        
        .no-files p {
            color: var(--text-light);
            max-width: 500px;
            margin: 0 auto;
            line-height: 1.6;
        }
        
        .footer {
            text-align: center;
            margin-top: 40px;
            padding-top: 20px;
            color: var(--text-light);
            font-size: 0.9rem;
            width: 100%;
        }
        
        @media (max-width: 768px) {
            .container {
                padding: 0;
            }
            
            header {
                padding: 20px 0;
                margin-bottom: 20px;
            }
            
            h1 {
                font-size: 2rem;
            }
            
            .card {
                padding: 20px;
                border-radius: 12px;
            }
            
            .card-header {
                flex-direction: column;
                align-items: flex-start;
            }
            
            .file-table th, .file-table td {
                padding: 14px 10px;
            }
            
            .file-link {
                gap: 10px;
            }
            
            .file-icon {
                width: 36px;
                height: 36px;
                font-size: 0.95rem;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>文件下载中心</h1>
            <p class="subtitle">简洁高效的文件管理平台，所有备份文件均可直接下载</p>
        </header>
        
        <div class="card">
            <div class="card-header">
                <div>
                    <h2 class="card-title">备份文件</h2>
                    <div class="file-count">共 )" << arr.size() << R"( 个文件</div>
                </div>
                
                <div class="controls">
                    <div class="search-box">
                        <i class="fas fa-search"></i>
                        <input type="text" id="searchInput" placeholder="搜索文件名...">
                    </div>
                    
                    <div class="sort-options">
                        <button class="sort-btn" data-sort="name">
                            <i class="fas fa-sort-alpha-down"></i> 文件名
                        </button>
                        <button class="sort-btn" data-sort="date">
                            <i class="fas fa-calendar-alt"></i> 修改时间
                        </button>
                        <button class="sort-btn" data-sort="size">
                            <i class="fas fa-sort-amount-down"></i> 文件大小
                        </button>
                    </div>
                </div>
            </div>
            
            <div class="table-container">
                <table class="file-table">
                    <thead>
                        <tr>
                            <th data-sort="name">文件</th>
                            <th data-sort="date">修改时间</th>
                            <th data-sort="size">大小</th>
                        </tr>
                    </thead>
                    <tbody id="fileTableBody">
    )";

    // 文件类型图标映射
    std::unordered_map<std::string, std::string> iconMap = {
        {".pdf", "fa-file-pdf"},
        {".doc", "fa-file-word"},
        {".docx", "fa-file-word"},
        {".xls", "fa-file-excel"},
        {".xlsx", "fa-file-excel"},
        {".zip", "fa-file-archive"},
        {".rar", "fa-file-archive"},
        {".tar", "fa-file-archive"},
        {".gz", "fa-file-archive"},
        {".jpg", "fa-file-image"},
        {".jpeg", "fa-file-image"},
        {".png", "fa-file-image"},
        {".gif", "fa-file-image"},
        {".mp4", "fa-file-video"},
        {".avi", "fa-file-video"},
        {".mov", "fa-file-video"},
        {".mp3", "fa-file-audio"},
        {".wav", "fa-file-audio"},
        {".txt", "fa-file-alt"},
        {".log", "fa-file-alt"}
    };

    for (int i = 0; i < arr.size(); i++) {
        // 获取文件名
        std::string filename = FileUtil(arr[i].real_path).FileName();
        
        // 获取文件扩展名
        std::string extension = "";
        size_t dotPos = filename.find_last_of('.');
        if (dotPos != std::string::npos) {
            extension = filename.substr(dotPos);
        }
        
        // 获取文件类型图标
        std::string iconClass = "fa-file";
        if (iconMap.find(extension) != iconMap.end()) {
            iconClass = iconMap[extension];
        }
        
        // 格式化文件大小
        std::string sizeDisplay;
        double sizeKB = arr[i].fsize / 1024.0;
        if (sizeKB < 1024) {
            sizeDisplay = std::to_string(static_cast<int>(sizeKB)) + " KB";
        } else {
            double sizeMB = sizeKB / 1024.0;
            char buf[20];
            snprintf(buf, sizeof(buf), "%.1f MB", sizeMB);
            sizeDisplay = buf;
        }
        
        ss << "<tr data-name=\"" << filename << "\" data-date=\"" << arr[i].mtime 
           << "\" data-size=\"" << arr[i].fsize << "\">";
        
        // 文件名列
        ss << "<td><a href=\"" << arr[i].url << "\" class=\"file-link\">"
           << "<div class=\"file-icon\"><i class=\"fas " << iconClass << "\"></i></div>"
           << "<div class=\"file-name\">"
           << "<span title=\"" << filename << "\">" << filename << "</span>"
           << "<small>" << extension << "</small>"
           << "</div></a></td>";
        
        // 修改时间列
        ss << "<td class=\"file-date\">" << TimeToStr(arr[i].mtime) << "</td>";
        
        // 文件大小列
        ss << "<td class=\"file-size\">" << sizeDisplay << "</td>";
        
        ss << "</tr>";
    }

    if (arr.empty()) {
        ss << "<tr><td colspan=\"3\"><div class=\"no-files\">"
           << "<i class=\"fas fa-cloud-download-alt\"></i>"
           << "<h3>没有找到备份文件</h3>"
           << "<p>当前没有可用的备份文件，请稍后再试或联系管理员</p></div></td></tr>";
    }

    ss << R"(
                    </tbody>
                </table>
            </div>
        </div>
        
        <div class="footer">
            <p>文件备份服务 &copy; 2023 | 最后更新: )" << TimeToStr(time(nullptr)) << R"(</p>
        </div>
    </div>
    
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const searchInput = document.getElementById('searchInput');
            const tableBody = document.getElementById('fileTableBody');
            const rows = Array.from(tableBody.querySelectorAll('tr'));
            const sortButtons = document.querySelectorAll('.sort-btn');
            const tableHeaders = document.querySelectorAll('.file-table th');
            
            // 搜索功能
            searchInput.addEventListener('input', function() {
                const searchTerm = this.value.toLowerCase();
                
                rows.forEach(row => {
                    if (row.querySelector('.no-files')) return;
                    
                    const fileName = row.dataset.name.toLowerCase();
                    if (fileName.includes(searchTerm)) {
                        row.style.display = '';
                    } else {
                        row.style.display = 'none';
                    }
                });
            });
            
            // 排序功能
            let currentSort = { column: 'name', ascending: true };
            
            function sortTable(column, ascending) {
                // 过滤掉无文件的行
                const sortableRows = rows.filter(row => !row.querySelector('.no-files'));
                
                sortableRows.sort((a, b) => {
                    let aValue, bValue;
                    
                    if (column === 'name') {
                        aValue = a.dataset.name.toLowerCase();
                        bValue = b.dataset.name.toLowerCase();
                    } else if (column === 'date') {
                        aValue = parseInt(a.dataset.date);
                        bValue = parseInt(b.dataset.date);
                    } else if (column === 'size') {
                        aValue = parseInt(a.dataset.size);
                        bValue = parseInt(b.dataset.size);
                    }
                    
                    if (aValue < bValue) return ascending ? -1 : 1;
                    if (aValue > bValue) return ascending ? 1 : -1;
                    return 0;
                });
                
                // 清空表格并重新添加排序后的行
                while (tableBody.firstChild) {
                    tableBody.removeChild(tableBody.firstChild);
                }
                
                sortableRows.forEach(row => {
                    tableBody.appendChild(row);
                });
                
                // 如果有无文件的行，重新添加
                const noFilesRow = rows.find(row => row.querySelector('.no-files'));
                if (noFilesRow) {
                    tableBody.appendChild(noFilesRow);
                }
            }
            
            // 排序按钮事件
            sortButtons.forEach(button => {
                button.addEventListener('click', function() {
                    const column = this.dataset.sort;
                    
                    // 更新当前排序状态
                    if (currentSort.column === column) {
                        currentSort.ascending = !currentSort.ascending;
                    } else {
                        currentSort = { column: column, ascending: true };
                    }
                    
                    // 更新按钮状态
                    sortButtons.forEach(btn => btn.classList.remove('active'));
                    this.classList.add('active');
                    
                    // 更新排序图标
                    const icon = this.querySelector('i');
                    if (column === 'name') {
                        icon.className = currentSort.ascending ? 
                            'fas fa-sort-alpha-down' : 'fas fa-sort-alpha-up';
                    } else {
                        icon.className = currentSort.ascending ? 
                            'fas fa-sort-amount-down' : 'fas fa-sort-amount-up';
                    }
                    
                    // 执行排序
                    sortTable(column, currentSort.ascending);
                });
            });
            
            // 表头排序事件
            tableHeaders.forEach(header => {
                header.addEventListener('click', function() {
                    const column = this.dataset.sort;
                    const button = document.querySelector(`.sort-btn[data-sort="${column}"]`);
                    if (button) button.click();
                });
            });
        });
    </script>
</body>
</html>
    )";

    rsp.body = ss.str();
    rsp.set_header("Content-Type", "text/html");
    rsp.status = 200;
        }


        static void UpLoad(const httplib::Request& req,httplib::Response& rsp)
        {
            bool ret=req.has_file("file");
            if(ret==false)
            {
                rsp.status=400;
                return;
            }

            const auto& file=req.get_file_value("file");
            std::cout<<file.filename<<std::endl;
            std::cout<<file.name<<std::endl;
            FileUtil tmp(file.filename);
            std::string filename=Config::GetInstance()->GetBackDir()+tmp.FileName();
            FileUtil fu(filename);
            fu.SetContent(file.content);

            BackupInfo info;
            info.NewBackupInfo(filename);
            _data->Insert(info);
            rsp.status=200;

        }
    private:
        std::string _server_ip;
        int _server_port;
        std::string _download_prefix;
        httplib::Server _server;
    };
}



#endif